import path from 'path';
import json from '@rollup/plugin-json';
import nodeResolve from '@rollup/plugin-node-resolve';
import ts from 'rollup-plugin-typescript2';
import { terser } from "rollup-plugin-terser";

// process.env.TARGET 是 获取 build.js 中 build 中 rollup 的配置

// 获取 packages
const packagesDir = path.resolve(__dirname, 'packages');
// 拿到需要打包的某个包
const packageDir = path.resolve(packagesDir, process.env.TARGET);

const resolve = _path => path.resolve(packageDir, _path);
console.log(process.env.TARGET)
const pkg = require(resolve('package.json'));
const name = path.basename(packageDir);

const outputConfig = {
  'esm-bundler': {
    file: resolve(`dist/${name}.esm-bundler.js`),
    format: 'es'
  },
  cjs: {
    file: resolve(`dist/${name}.cjs.js`),
    format: 'cjs'
  },
  global: {
    file: resolve(`dist/${name}.global.js`),
    format: 'iife'
  }
}

// 自定义的打包的配置项
const options = pkg.buildOptions;
function createConfig(format, output) {
  output.name = options.name;
  // 是否生成 sourcemap
  output.sourcemap = true;
  // 生成 rollup 
  return {
    input: resolve(`src/index.ts`),
    output,
    plugins: [
      json(),
      ts({
        tsconfig: path.resolve(__dirname, 'tsconfig.json')
      }),
      nodeResolve()
    ]
  }
}

export default options.formats.map(format => createConfig(format, Object.assign(outputConfig[format], {
  plugins: [
    process.env.NODE_ENV === "development" ? null : terser()
  ],
  banner: "/* min-vue3 version " + pkg.version + " */",
  footer: "/* follow me on Twitter! @Tom */",
})));

